
var box = document.getElementById('box');
var smallBox = document.getElementById('smallBox');
var bigBox = document.getElementById('bigBox');
var mask = document.getElementById('mask');
var bigImage = document.getElementById('bigImage');

smallBox.onmouseover = function () {
    bigBox.style.display = "block";
    mask.style.display = "block";
}

smallBox.onmouseout = function () {
    bigBox.style.display = "none";
    mask.style.display = "none";
}

smallBox.onmousemove = function (e) {
    /* 
        获取鼠标位置
    */
    var e = e || window.event;
    var pageX = e.pageX || e.clientX + document.documentElement.scrollLeft;
    var pageY = e.pageY || e.clientY + document.documentElement.scrollTop;
    /*
        获取鼠标在盒子中的位置 = 鼠标位置 - 最外边盒子(在这里是box)外边框到定位父级(在这里是body)的左内边框的距离
    */
    var boxX = pageX - box.offsetLeft;
    var boxY = pageY - box.offsetTop;
    /*
        用鼠标在盒子中的位置减去mask自身宽高的一半，再赋值给mask，在css文件中设置了smallBox的定位relative，mask的定位absolute
    */
    var maskX = boxX - mask.offsetWidth / 2;
    var maskY = boxY - mask.offsetHeight / 2
    /*
        设置边界
    */
    if (maskX < 0) maskX = 0;
    if (maskX > smallBox.offsetWidth - mask.offsetWidth) maskX = smallBox.offsetWidth - mask.offsetWidth;
    if (maskY < 0) maskY = 0;
    if (maskY > smallBox.offsetHeight - mask.offsetHeight) maskY = smallBox.offsetHeight - mask.offsetHeight;
    mask.style.left = maskX + "px";
    mask.style.top = maskY + "px";
    /* 
        rate = 大图能够移动的总距离 / mask能够移动的总距离
        大图能够移动的总距离 = 大图的宽度 - 大盒子bigBox的宽度
        mask能够移动的总距离 = 小盒子的宽度 - mask的宽度
        大图应该到的位置 = rate * mask当前位置
    */
    var bigToMove = bigImage.offsetWidth - bigBox.offsetWidth;
    var maskToMove = smallBox.offsetWidth - mask.offsetWidth;
    var rate = bigToMove / maskToMove;
    bigImage.style.left = -rate * maskX + "px";
    bigImage.style.top = -rate * maskY + "px";
}